<?php

class App_Auth_Adapter_Web implements Zend_Auth_Adapter_Interface
{
	private $_username;
	private $_password;

    /**
     * Sets username and password for authentication
     *
     * @return void
     */
    public function __construct($username, $password)
    {
		$this->_username = $username;
		$this->_password = $password;
	}

	public function getIdentity(){
		return $this->_username;
	}

    /**
     * Performs an authentication attempt
     *
     * @throws Zend_Auth_Adapter_Exception If authentication cannot be performed
     * @return Zend_Auth_Result
     */
    public function authenticate()
    {
        // get the user info from the database (username is an email address)
        $user = Doctrine_Core::getTable("Users")->findOneByUsername($this->_username);
        if (!$user) {
        	// user name (email) not found
            return new Zend_Auth_Result(
            	Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND,
                array('user_name'=>$this->_username), 
                array('invalid username')
            );
		}

        // make a hash using the salt from the database
        $signature = strtolower(md5($this->_password . $user->salt));

        // validate credentials
		if ($signature !== $user->password){
			// password is not valid...
			return new Zend_Auth_Result(
				Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
				array('user_name'=>$this->_username), 
				array('invalid credentials')
			);
		}

		return new Zend_Auth_Result(
			Zend_Auth_Result::SUCCESS,
            array(
            	'user_name'=>$this->_username,
            	'user_first_name'=>$user->first_name,
            	'user_last_name'=>$user->last_name,
            	'user_id'=>$user->id_user,
                'user_role'=>$user->id_role,
                'last_login_at'=>$user->last_login_at
            ),
            array('successful login')
        );

    }
}
